<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <div id="app">
        <input type="file" class="upload" @change="upload">
        <img :src="img" alt="">
    </div>
    <script>
        const { createApp } = Vue
        createApp({
            data() {
                return {
                    img: '',
                }
            },
            methods: {
                upload(event) {
                    //获取选中的文件
                    const file = event.target.files[0];
                    if (file) {
                        const reader = new FileReader();
                        // 读取文件为 Data URL
                        reader.readAsDataURL(file);
                        reader.onload = () => {
                            // 将读取的 Data URL 赋值给 img 变量
                            this.img = reader.result;
                        };
                    }
                    else {
                        console.log('请选择一个文件');
                    }

                    // const file = event.target.files[0];
                    // if (!file) {
                    //     console.log('请选择一个文件');
                    //     return;
                    // }
                    // const fd = new FormData();
                    // fd.append('file', event.target.files[0]);
                    // axios({
                    //     url: 'http://hmajax.itheima.net/api/uploadimg',
                    //     method: 'post',
                    //     data: fd
                    // }).then(res => {
                    //     console.log(res);
                    //     this.img = res.data.data.url;
                    // }).catch(error => {
                    //     console.error('上传文件时出错:', error);
                    // });
                }
            }
        }).mount('#app')
    </script>
</body>

</html>